<template>
  <div>
    <page-list :x-uri="uri" :x-tabs="tabs" :doactions="doactions" :tree="true" :lazy="true" :lazy-fun="loadChild">
      <!-- 页面操作按钮 -->
      <template v-slot:page-button>
        <el-button v-auth="'course.category.create'" size="mini" type="primary" @click="create">新建分类</el-button>
      </template>
    </page-list>
    <el-dialog
      title="请输入分类名称"
      :visible.sync="dialogVisible"
      width="742px"
      :close-on-click-modal="false"
      top="30vh"
    >
      <el-form v-if="dialogVisible" ref="category" :model="category" size="small">
        <el-form-item v-if="category.id" prop="title" :rules="rulesTtitle">
          <edu-input key="title" :value.sync="category.title" :args="{ minlength: 2, maxlength: 30 }" />
        </el-form-item>
        <el-form-item v-else prop="title" :rules="batchRulesTtitle">
          <el-input v-model="category.title" type="textarea" :autosize="{ minRows: 8, maxRows: 20}"></el-input>
          <div class="edu-tips">支持添加多个分类名称，一行为一个分类名称</div>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="end">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" :disabled="disableSubmit" @click="onSubmit">保存</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import PageList from '@public/template/page_list.vue'
import EduInput from '@public/form/input.vue'
import { mapState } from 'vuex'
export default {
  components: {
    PageList,
    EduInput
  },
  inject: ['reload'],
  data() {
    return {
      uri: 'course/admin/category/list',
      tabs: [
        {
          title: '分类列表',
          uri: '/course/category/list',
          meta: {
            permission: 'course.category.list'
          }
        }
      ],
      doactions: [
        { title: '添加子分类', meta: { permission: 'course.category.create' }, callback: this.addChildren },
        { title: '编辑', meta: { permission: 'course.category.edit' }, callback: this.edit },
        { title: '删除', meta: { permission: 'course.category.delete' }, callback: this.deleteCategory }
      ],
      dialogVisible: false,
      disableSubmit: false,
      category: {
        pid: 0,
        title: ''
      },
      rulesTtitle: [
        { required: true, message: '分类名称必须填写', trigger: ['blur', 'change'] },
        {
          pattern: /^.{2,30}$/,
          message: '分类名称为2-30个字符',
          trigger: ['blur', 'change']
        }
      ],
      batchRulesTtitle: [
        { required: true, message: '分类名称必须填写', trigger: ['blur', 'change'] },
        {
          trigger: ['blur', 'change'],
          validator: (rule, value, callback) => {
            const arr = value.toString().split('\n')
            arr.forEach(v => {
              const reg = /^.{2,30}$/
              if (!reg.test(v)) {
                return callback(new Error('单个分类名称为2-30个字符'));
              }
            })
              // return callback(new Error('请填写驳回理由'))
            callback()
          }
        }
      ]
    }
  },
  computed: {
    ...mapState('pageList', {
      pageData: 'responseData'
    })
  },
  methods: {
    create: function() {
      this.category = {
        pid: 0,
        title: ''
      }
      this.dialogVisible = true
    },
    addChildren: function({ row }) {
      this.category = {
        pid: row.id,
        title: ''
      }
      this.dialogVisible = true
    },
    edit: function({ row }) {
      this.category = {
        id: row.id,
        title: row.title
      }
      this.dialogVisible = true
    },
    onSubmit: function() {
      this.$refs['category'].validate((valid) => {
        if (valid) {
          this.disableSubmit = true
          var method = 'POST'
          var uri = '/course/admin/category/create'
          if (this.category.id) {
            method = 'PUT'
            uri = '/course/admin/category/' + this.category.id
          }
          this.$http.send(
            method,
            uri,
            this.category,
            (response) => {
              this.$message.success(response.msg, (_) => {
                this.reload()
              })
            },
            (error) => {
              this.disableSubmit = false
              this.$message.error(error.msg)
            }
          )
        }
      })
    },
    deleteCategory: function({ row }) {
      this.$box
        .confirm('确认删除吗')
        .then(() => {
          this.$http.delete(
            '/course/admin/category/' + row.id,
            {},
            (response) => {
              this.$message.success(response.msg, (_) => {
                this.reload()
              })
            },
            (error) => {
              this.$message.error(error.msg)
            }
          )
        })
        .catch(() => {})
    },
    loadChild: function(row, treeNode, resolve) {
      this.$http.get(
        '/course/admin/category/' + row.id + '/children',
        {
          pid: row.id
        },
        ({ data }) => {
          resolve(data)
        },
        (response) => {
          resolve([])
          this.$message.error(response.msg)
        },
        false
      )
    }
  }
}
</script>
